<?php
declare (strict_types=1);

namespace app\course\service\live\admin;

use app\admin\logic\system\Config as SystemConfig;
use app\common\service\BaseService;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\page\PageForm;
use think\Request;
use think\Response;

/**
 * 直播相关配置
 */
class Config
{

    /**
     * 直播服务商
     *
     * @var []
     */
    protected $configKeyList = [
        '1' => 'course.live.config.tic',
        '2' => 'course.live.config.agora',
        '3' => 'course.live.config.cclive'
    ];

    /**
     * 腾讯TRTC
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/15
     *
     * @return Response
     */
    public function tic()
    {
        $key    = $this->configKeyList['1'];
        $fields = [
            'sdk_appid' => FormItem::make()->title('SDKAppID')->help('1. 前往 <a href="https://console.cloud.tencent.com/trtc/app" target="_blank" class="el-link el-link--primary">腾讯云-实时音视频</a> 创建应用<br />2. 在应用列表可获得SDKAppID信息'),
            'key'       => FormItem::make()->title('密钥')->help('1. 前往 <a href="https://console.cloud.tencent.com/trtc/app" target="_blank" class="el-link el-link--primary">腾讯云-实时音视频</a> 查看创建的应用列表<br />2. 在【应用列表->应用信息->快速上手】中，第二步可看到密钥并复制到这里'),
            'is_open'   => FormItem::make('slideSwitch')->title('启用')->activeValue(1)->inactiveValue(0)->help('1. 直播服务商只能同时启用一个<br />2. 启用前，请确保app打包的直播sdk是腾讯云服务商')
        ];

        $form          = new PageForm();
        $form->pageKey = $fields;
        $form->withSystemConfig();
        $config          = SystemConfig::get($key, []);
        $config['__key'] = $key;
        $form->datas     = $config;

        return $form->send();
    }

    /**
     * 声网
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/15
     *
     * @return Response
     */
    public function agora()
    {
        $key    = $this->configKeyList['2'];
        $help   = '1. 使用白板时必填<br />2. 前往 <a href="https://oss.console.aliyun.com/bucket" target="_blank" class="el-link el-link--primary">阿里云OSS</a> 配置';
        $fields = [
            'appid'           => FormItem::make()->title('AppID')->required()->help('请联系Eduline客服'),
            'auth'            => FormItem::make()->title('Auth')->required()->help('请联系Eduline客服'),
            'netless_appid'   => FormItem::make()->title('NetlessAppID')->required()->help('请联系Eduline客服'),
            'netless_token'   => FormItem::make()->title('NetlessSDKToken')->required()->help('请联系Eduline客服'),
            'accessKeyId'     => FormItem::make()->title('accessKeyId')->help($help),
            'accessKeySecret' => FormItem::make()->title('accessKeySecret')->help($help),
            'region'          => FormItem::make()->title('region')->help($help),
            'bucket'          => FormItem::make()->title('bucket')->help($help),
            'folder'          => FormItem::make()->title('folder')->help($help),
            'prefix'          => FormItem::make()->title('prefix')->help($help),
            'is_open'         => FormItem::make('slideSwitch')->title('启用')->activeValue(1)->inactiveValue(0)->help('1. 直播服务商只能同时启用一个<br />2. 启用前，请确保app打包的直播sdk是声网服务商')
        ];

        $form              = new PageForm();
        $form->pageKey     = $fields;
        $form->saveMethod  = 'POST';
        $form->savePostUrl = '/course/admin/live/config/save';
        $config            = SystemConfig::get($key, []);
        $config['__key']   = $key;
        $config['is_open'] = $this->getUsedLiveProviderId() === 2 ? 1 : 0;
        $config            = array_merge($config, SystemConfig::get('course.live.config.netless', []));
        $form->datas       = $config;

        return $form->send();
    }

    /**
     * CC直播
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/15
     *
     * @return Response
     */
    public function cclive()
    {
        $key  = $this->configKeyList['3'];
        $url1 = 'https://console.bokecc.com/live/developSettings/API';
        // $url2   = 'https://console.bokecc.com/class/developer-center/developerCenterKeyManage';
        $help   = '前往 <a href="' . $url1 . '" target="_blank" class="el-link el-link--primary"> CC - API接口 </a> 获取';
        $fields = [
            'UserID'      => FormItem::make()->title('UserID')->required()->help($help),
            'APIKey'      => FormItem::make()->title('云直播APIKey')->required()->help($help),
            'classAPIKey' => FormItem::make()->title('云课堂APIKey')->required()->help($help),
            'is_open'     => FormItem::make('slideSwitch')->title('启用')->activeValue(1)->inactiveValue(0)->help('1. 直播服务商只能同时启用一个<br />2. 启用前，请确保app打包的直播sdk是CC服务商')
        ];

        $form              = new PageForm();
        $form->pageKey     = $fields;
        $form->saveMethod  = 'POST';
        $form->savePostUrl = '/course/admin/live/config/save';
        $config            = SystemConfig::get($key, [], request()->mhm_id, true);
        $config['__key']   = $key;
        $config['is_open'] = $this->getUsedLiveProviderId() === 3 ? 1 : 0;
        $form->datas       = $config;

        return $form->send();
    }

    /**
     * 保存配置
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/15
     *
     * @param Request $request
     * @return Response
     */
    public function saveConfig(Request $request)
    {
        $data = $request->post();
        $key  = $data['__key'];
        // 移除key
        unset($data['__key']);
        // 是否存在配置启动状态
        if (isset($data['is_open'])) {
            $providerId = array_search($key, $this->configKeyList);
            $config     = SystemConfig::get('live_provider_used', ['provider_id' => 0]);
            $configId   = $config['provider_id'] ?? 0;
            // 修改直播服务商
            if ($providerId == $configId || $data['is_open'] === 1) {
                $providerId = $data['is_open'] === 1 ? $providerId : 0;
                SystemConfig::set('live_provider_used', ['provider_id' => $providerId]);
            }
        }
        switch ($key) {
            case $this->configKeyList['2']:
                // 声网,需要分开存
                $agora   = [
                    'appid'         => $data['appid'],
                    'auth'          => $data['auth'],
                    'netless_appid' => $data['netless_appid'],
                    'netless_token' => $data['netless_token']
                ];
                $netless = [
                    'accessKeyId'     => $data['accessKeyId'] ?? '',
                    'accessKeySecret' => $data['accessKeySecret'] ?? '',
                    'region'          => $data['region'] ?? '',
                    'bucket'          => $data['bucket'] ?? '',
                    'folder'          => $data['folder'] ?? '',
                    'prefix'          => $data['prefix'] ?? '',
                ];
                SystemConfig::set($this->configKeyList[2], $agora);
                SystemConfig::set('course.live.config.netless', $netless);
                break;
            default:
                if (isset($data['is_open'])) {
                    unset($data['is_open']);
                }
                SystemConfig::set($key, $data);
                break;
        }

        return BaseService::parseToData([], 1, '保存成功');

    }

    /**
     * 获取正在使用的服务商ID
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/15
     *
     * @return mixed
     */
    protected function getUsedLiveProviderId()
    {
        $config = SystemConfig::get('live_provider_used', ['provider_id' => 0]);

        return intval($config['provider_id']);
    }
}
